package priv.menghan.clock;

import javazoom.jl.player.Player;

import javax.swing.*;
import java.awt.*;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Clock extends JFrame {
    private static final Logger LOGGER = Logger.getLogger(Clock.class.getName()); // 日志对象
    private final JLabel timeLabel;
    private final SimpleDateFormat timeFormat;
    private final JTextField timerField;
    Player player;
    private Timer countdownTimer;
    private int countdownSeconds;

    public Clock() {
        setTitle("时钟");
        setSize(300, 200);
        setDefaultCloseOperation(EXIT_ON_CLOSE); // 改为不立即关闭

        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        timeFormat = new SimpleDateFormat("HH:mm:ss");
        timeLabel = new JLabel();
        timeLabel.setFont(new Font("Arial", Font.BOLD, 40));
        timeLabel.setHorizontalAlignment(SwingConstants.CENTER);
        add(timeLabel, BorderLayout.CENTER);

        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout());

        timerField = new JTextField(5);
        panel.add(timerField);

        JButton setTimerButton = createSetTimerButton(); // 调用提取的方法
        panel.add(setTimerButton);

        add(panel, BorderLayout.SOUTH);

        Timer timer = new Timer(1000, _ -> updateTime());
        timer.start();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new Clock().setVisible(true));
    }

    private void updateTime() {
        String currentTime = timeFormat.format(new Date());
        timeLabel.setText(currentTime);
    }

    private void startCountdown() {
        countdownTimer = new Timer(1000, _ -> {
            countdownSeconds--;
            if (0 >= countdownSeconds) {
                countdownTimer.stop();
                playMP3Async();
                JOptionPane.showMessageDialog(Clock.this, "时间到！", "提示", JOptionPane.INFORMATION_MESSAGE);
                stopMP3();
            }
        });
        countdownTimer.start();
    }

    private void playMP3Async() {
        SwingWorker<Void, Void> worker = new SwingWorker<>() {
            @Override
            protected Void doInBackground() {
                playMP3("static/qiansixian.mp3");
                return null;
            }
        };
        worker.execute();
    }

    public void playMP3(final String mp3File) {
        try {
            InputStream inputStream = this.getClass().getResourceAsStream("/" + mp3File);
            if (inputStream != null) {
                player = new Player(inputStream);
            }
            player.play();
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "播放MP3文件时发生错误: " + mp3File, e);
        }
    }

    public void stopMP3() {
        if (null != this.player) {
            player.close();
            player = null;
        }
    }

    // 提取的按钮创建方法
    private JButton createSetTimerButton() {
        JButton button = new JButton("设置定时");
        button.addActionListener(_ -> {
            try {
                countdownSeconds = Integer.parseInt(timerField.getText());
                if (0 < countdownSeconds) {
                    startCountdown();
                } else {
                    JOptionPane.showMessageDialog(this, "请输入有效的秒数", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "请输入有效的秒数", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
        return button; // 返回按钮实例
    }
}
